package cn.com.callback

import cn.com.callback.CallBackInvoke
import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import cn.com.kh.KHSWUtil
import cn.com.kh.KHUtil
import net.sf.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.jdbc.core.JdbcTemplate

/**
 * @projectName: ngsapitask-sw
 * @className: autoUnicomSMSSend
 * @author: LiJT
 * @description: 联通短信平台发送短信(非催缴)
 * @date: 2022-09-27 00:12
 * @version: 1.0
 */

public class autoUnicomSMSSend implements CallBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoUnicomSMSSend.class);

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        log.debug("短信平台发送短信(非催缴)-开始执行------------------------------");

        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 两次发送失败再次发送间隔
        int getResInterval = 30;
        String getResIntervalDB = KHDBConfig.getParamConfig(eliteBean, "getResInterval");
        if (!KHUtil.isNull(getResIntervalDB)) {
            getResInterval = Integer.parseInt(getResIntervalDB);
        }

        // 普通短信每批次发送数量限制
        String SMS_SendNumLimit = KHDBConfig.getParamConfig(eliteBean, "SMS_SendNumLimit");

        if (KHUtil.isNull(SMS_SendNumLimit)) {
            SMS_SendNumLimit = 100;
        }
        log.debug("短信平台发送短信(非催缴)-单轮次发送数量限制:" + SMS_SendNumLimit+" 失败重试间隔秒:" + SMS_SendNumLimit);

        int whileNum = 0;
        boolean isContinue = true;
        try {
            while (isContinue) {
                whileNum++;

                try {
                    log.debug("短信平台发送短信(非催缴)-当前短信轮次:" + whileNum);
                    String selectDocumentoutSQL = '''Select Top ''' + SMS_SendNumLimit + ''' R1.Documentout_Guid,
                                                       R1.Documentto,
                                                       Case
                                                         When Charindex('【深圳水务集团】', R1.Documentpath) <= 0 Then
                                                          '【深圳水务集团】' + R1.Documentpath
                                                         Else
                                                          R1.Documentpath
                                                       End As Documentpath,
                                                       Isnull(R2.Sms_Send_Type, 'CRM人工短信') As Sms_Send_Type,
                                                       R1.Account_Guid,
                                                       R1.Sms_Guid,
                                                       Isnull(R2.Send_Priority, 99) As Priority,
                                                       R1.Createdby,
                                                       R1.Subscriber_Guid
                                                  From Documentout R1 With(Nolock)
                                                  Left Join Sw_Sms_Config_Map R2 With(Nolock)
                                                    On R1.Stringfield1 = R2.Crm_Sms_Type
                                                 Where R1.Doctype = 3
                                                   And R1.Passflag Is Null
                                                   And Isnumeric(R1.Documentto) = 1
                                                   And Isnull(R1.Expectedstartdate, Getdate()) <= Getdate()
                                                   And Isnull(R1.Trialcount, 0) < Isnull(R1.Trialcountlimit, 3)
                                                   And (Dateadd(Ss, ''' + getResInterval + ''' * Isnull(R1.Trialcount, 0), R1.Lasttrydatetime) <= Getdate() Or R1.Lasttrydatetime Is Null Or R1.Lasttrydatetime = '')
                                                 Order By Priority, Isnull(R1.Expectedstartdate, Getdate()), R1.Createddate''';

                    List<Map<String, Object>> selectDocumentoutList = jt.queryForList(selectDocumentoutSQL);
                    int ListNum = selectDocumentoutList.size();
                    log.debug("短信平台发送短信(非催缴)-待发送短信数量ListNum:" + ListNum);

                    String updateDocSQL = "";

                    String Documentout_Guid = "";
                    String Documentto = "";
                    String Documentpath = "";
                    String Account_Guid = "";
                    String Sms_Send_Type = "";
                    String userMsgId = "";
                    for (int i = 0; i < ListNum; i++) {
                        Map selectDocumentoutSQLMap = selectDocumentoutList.get(i);

                        Documentout_Guid = selectDocumentoutSQLMap.get("Documentout_Guid");
                        Documentto = selectDocumentoutSQLMap.get("Documentto");// 手机号码
                        Documentpath = selectDocumentoutSQLMap.get("Documentpath");// 短信内容
                        Account_Guid = selectDocumentoutSQLMap.get("Account_Guid");// 短信发送使用账号
                        Sms_Send_Type = selectDocumentoutSQLMap.get("Sms_Send_Type");// 短信类型批次名称
                        userMsgId = selectDocumentoutSQLMap.get("userMsgId");// 短信拓展ID

                        userMsgId = KHUtil.isNull(userMsgId) ? KHUtil.getRandomString(20) : userMsgId;

                        // 调用发送短信
                        JSONObject sendResultJson = KHSWUtil.sendSWSms(eliteBean, Documentout_Guid, Documentto, Documentpath, Account_Guid, Sms_Send_Type, userMsgId, "");

                        // 解析返回信息LockedBy
                        String resCode = sendResultJson.has("code") ? sendResultJson.getString("code") : "-1";
                        String resDesc = sendResultJson.has("msg") ? sendResultJson.getString("msg") : "";

                        if (resCode == "0") {
                            String msgId = sendResultJson.has("msgId") ? sendResultJson.getString("msgId") : "";
                            updateDocSQL = '''Update Documentout
                                               Set Status          = 1,
                                                   Passflag        = 1,
                                                   Resultcode      = ?,
                                                   Lasttrydatetime = Getdate(),
                                                   Modifiedby      = 'SELITE',
                                                   Modifieddate    = Getdate(),
                                                   Failcode        = ?,
                                                   Faildescription = ?,
                                                   Trialcount      = Isnull(Trialcount, 0) + 1,
                                                   Usermsgid       = ?
                                             Where Documentout_Guid = ?''';

                            int updateDocSQLRes = jt.update(updateDocSQL, msgId, resCode, resDesc, userMsgId, Documentout_Guid);
                            log.debug("短信平台发送短信(非催缴)-短信平台回写Documentout表SQL执行结果:" + updateDocSQLRes);

                        } else {
                            updateDocSQL = '''Update Documentout
                                               Set Status = Case
                                                              When Isnull(Trialcount, 0) + 1 >= Isnull(Trialcountlimit, 3) Then
                                                               '-1'
                                                              Else
                                                               Status
                                                            End,
                                                   Failcode        = ?,
                                                   Faildescription = ?,
                                                   Trialcount      = Isnull(Trialcount, 0) + 1,
                                                   Lasttrydatetime = Getdate(),
                                                   Usermsgid       = ?
                                             Where Documentout_Guid = ?''';

                            int updateDocSQLRes = jt.update(updateDocSQL, resCode, resDesc, userMsgId, Documentout_Guid);
                            log.debug("短信平台发送短信(非催缴)-短信平台回写Documentout表SQL执行结果:" + updateDocSQLRes);
                        }

                    }
                    if (ListNum <= 0 || whileNum >= 10) {
                        log.debug("短信平台发送短信(非催缴)-本次线程获取数量0或累计超10次循环-不满足继续执行...");
                        isContinue = false;
                    }
                } catch (Exception e) {
                    log.error("短信平台发送短信(非催缴)-异常信息：", e);
                    if (whileNum >= 10) {
                        log.warn("短信平台发送短信(非催缴)-本次线程累计超10次循环-不满足继续执行...");
                        isContinue = false;
                    }
                }
            }
            //智慧停水短信 发送成功标识更新
            log.debug("短信平台发送短信(非催缴)-智慧停水短信 发送成功标识更新...");
            String waterOffSmsbatchSQL = '''Update Wateroffsmsbatch
                                               Set Status = 2, Finishdate = Getdate()
                                             Where Sms_Guid In (Select Distinct Sms_Guid
                                                                  From Documentout With(Nolock)
                                                                 Where Stringfield1 = '智慧停水发送'
                                                                   And Passflag = '1'
                                                                   And Expectedstartdate > Getdate() - 1
                                                                 Group By Sms_Guid)''';

            int waterOffSmsbatchFlag = jt.update(waterOffSmsbatchSQL);
            log.debug("短信平台发送短信(非催缴)-智慧停水短信发送状态更新waterOffSmsbatch表SQL执行结果:" + waterOffSmsbatchFlag);

        } catch (Exception e) {
            log.error("短信平台发送短信(非催缴)-异常信息：", e);
        }

    }

}
